#include "stationview.h"
#include <QFile>
#include <QHBoxLayout>
#include <QApplication>
#include <QLabel>
#include <QMovie>
#include <QEvent>
#include <QBitmap>
#include <QSettings>
#include <QTextCodec>
#include "common.h"
#include "hqlabel.h"

extern int interval_unequal_offset;
extern int all_unequal_offset;

int StationView::m_id = qRegisterMetaType<StationView*>();

StationView::StationView(QWidget *parent)
    :ViewObject(parent)
    ,m_paramStationView(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_DeleteOnClose);

#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
        m_objectParam = new ParamObject;

    if (m_paramStationView == NULL)
        m_paramStationView = new StationViewParam;
}

StationView::~StationView()
{
    if (m_paramStationView != NULL)
        delete m_paramStationView;

    if (m_objectParam != NULL)
        delete  m_objectParam;

    m_objectParam = NULL;
    m_paramStationView = NULL;
}

void StationView::SetOffset(int offset)
{
    if (offset == 0) return;
    /*设置不等间距的偏移量*/
    int stid = m_objectParam->GetStId();
    int curr_id = mProtocolData->curr_or_next_id;
    int start_id = mProtocolData->start_id;
    int stop_id = mProtocolData->stop_id;
    int rundir = RUN_INVALID;
    if (start_id < stop_id)
        rundir = RUN_UP;
    else if (start_id > stop_id)
        rundir = RUN_DOWN;

    bool is_mirror = mProtocolData->file_path.contains("mirror");

    //当前站都是偏移一个偏移量
    if (curr_id == stid)
        mOffsetX = offset;

    //当前站后面的站都是偏移两个偏移量
    //上行或者下行镜像一组(大号在右侧)，下行或者上行镜像一组(小号在右侧)
    if ((is_mirror && rundir == RUN_DOWN) || (!is_mirror && rundir == RUN_UP))
    {
        if (stid > curr_id)
            mOffsetX = 2*offset;
    }
    else
    {
        if (stid < curr_id)
            mOffsetX = 2*offset;
    }
    /**************************************************/
}

QString StationView::FindCss(QString prefix, QString url_origin, QString url_with_suffix)
{
    Q_UNUSED(prefix);
    if (url_with_suffix == "" || ".gif" == url_with_suffix.right(4) || ".hqv" == url_with_suffix.right(4))
        return url_with_suffix;

    QStringList list = url_origin.split("_");
    if (list.size() < 4)
        return url_with_suffix;

    QString css_group = QString("%1_%2_%3_%4").arg(list.at(0)).arg(list.at(1)).arg(list.at(2)).arg(list.at(3));

    if (css_group == "")
        return url_with_suffix;

    return css_group + QString("##") + url_with_suffix;
}


QString StationView::FindHqt(QString prefix, QString url)
{
    QString filename = prefix + QString(StationNameConfigFile);

    QFileInfo fileInfo(filename);
    if (!fileInfo.isFile())
        return "";

    QStringList list = url.split("_");
    if (list.size() < 4)
        return "";

    if (url == "hide")
        return "";

    QSettings settings(filename, QSettings::IniFormat);
    settings.setIniCodec(QTextCodec::codecForName("utf-8"));

    QString name = "";
    QStringList grp_list = settings.childGroups();
    if (grp_list.contains(KEY_VALUE))
    {
        settings.beginGroup(KEY_VALUE);
        QString key = QString("name%1").arg(list.at(3));
        name = settings.value(key, "").toString();
        settings.endGroup();
    }

    if (name == "")
        return "";

    return name + QString(".hqt");
}

void StationView::ShowObject()
{ 
    if (!m_paramStationView || !m_objectParam) return;

    int stid = m_objectParam->GetStId();
    LoadStationPic(stid, mFilename);
    url = m_paramStationView->m_resNormalPath;

    int interval_config_offset = interval_unequal_offset;
    int all_config_offset = all_unequal_offset;

     if (mProtocolData)
     {
         int curr_id = mProtocolData->curr_or_next_id;
         LOG_QDEBUG << "curr_id:" << curr_id;
         int start_id = mProtocolData->start_id;
         int stop_id = mProtocolData->stop_id;
         int rundir = RUN_INVALID;
         if (start_id < stop_id)
             rundir = RUN_UP;
         else if (start_id > stop_id)
             rundir = RUN_DOWN;

         if (mFilename.contains(IntervalFlag))
             SetOffset(interval_config_offset);
         if (mFilename.contains(AllFlag))
             SetOffset(all_config_offset);

         if (curr_id == INVALID_NUM || stid == 0 || curr_id == 0)
         {
             url = m_paramStationView->m_resNormalPath;
         }
         else
         {
             LOG_QDEBUG << "stop_id:" << stop_id << "start_id:" << start_id << "curr_id:" << curr_id << "stid:" << stid;
             if (curr_id == stid)
             {
                 url = m_paramStationView->m_resCurrentPath;
             }
             else if (stid > curr_id)
             {
                 if (rundir == RUN_UP)
                 {
                     url =  m_paramStationView->m_resFuturePath;
                 }
                 else if (rundir == RUN_DOWN)
                 {
                     url =  m_paramStationView->m_resPassPath;
                 }
             }
             else if (stid < curr_id)
             {
                 if (rundir == RUN_UP)
                 {
                     url = m_paramStationView->m_resPassPath;
                 }
                 else if (rundir == RUN_DOWN)
                 {
                     url =  m_paramStationView->m_resFuturePath;
                 }
             }
             else
             {
                 url = m_paramStationView->m_resNormalPath;
             }
         }

         foreach (int id, mProtocolData->skip_list)
         {
             if (id == stid)
             {
                 url = m_paramStationView->m_resSkipPath;
                 break;
             }
         }

         if (rundir == RUN_UP)
         {
             if (url.contains("all_line") && stid == start_id)
             {
                 url = m_paramStationView->m_resCrossPath;
                 LOG_QDEBUG << "up 1 CrossPath";
             }
             if (stid < start_id || stid > stop_id)
             {
                 url = m_paramStationView->m_resCrossPath;
                 LOG_QDEBUG << "up 2 CrossPath";
             }
         }
         else if (rundir == RUN_DOWN)
         {
             if (url.contains("all_line") && stid == start_id)
             {
                 url = m_paramStationView->m_resCrossPath;
                 LOG_QDEBUG << "down 1 CrossPath";
             }
             if (stid > start_id || stid < stop_id)
             {
                 url = m_paramStationView->m_resCrossPath;
                 LOG_QDEBUG << "down 2 CrossPath";
             }
         }
     }
     else
     {
         url = m_paramStationView->m_resNormalPath;
     }

     ShowUrl();
}

void StationView::LoadStationPic(int stid, QString filename)
{
    //去除后缀.xml
    if (filename == "")
        return;

    QString file_name = filename.left(filename.size() - 4);
    QStringList list = file_name.split("_");
    QString flag = list.at(ParamType);

    m_paramStationView->m_resNormalPath  = QString("%1_station_future_%2").arg(flag).arg(stid);
    m_paramStationView->m_resFuturePath  = QString("%1_station_future_%2").arg(flag).arg(stid);
    m_paramStationView->m_resSkipPath    = QString("%1_station_skip_%2").arg(flag).arg(stid);
    m_paramStationView->m_resCurrentPath = QString("%1_station_current_%2").arg(flag).arg(stid);
    m_paramStationView->m_resCrossPath   = QString("%1_station_cross_%2").arg(flag).arg(stid);
    m_paramStationView->m_resPassPath    = QString("%1_station_pass_%2").arg(flag).arg(stid);
}

void StationView::GetAttribute(std::string &attribute)
{   
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();

    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void StationView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
         LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);

    if (CheckJsonValueType(root, "zindex", Json::stringValue))
         m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());

    if (CheckJsonValueType(root, "stid", Json::stringValue))
        m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());

    if (CheckJsonValueType(root, "idtype", Json::stringValue))
        m_objectParam->SetStIdType(QString::fromStdString(root["idtype"].asString()));

    if (CheckJsonValueType(root, "x", Json::stringValue))
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());

    if (CheckJsonValueType(root, "y", Json::stringValue))
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());

    if (CheckJsonValueType(root, "w", Json::stringValue))
        m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());

    if (CheckJsonValueType(root, "h", Json::stringValue))
        m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());

    if (CheckJsonValueType(root, "name", Json::stringValue))
        m_objectParam->SetName(QString::fromStdString(root["h"].asString()));
}

void StationView::ParseXML(QDomElement* xmlDomEle)
{
    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name",""));
}

void StationView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type", m_objectParam->GetObjectName());
    dom->setAttribute("zindex",QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid",QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x",QString::number(m_objectParam->GetX()));
    dom->setAttribute("y",QString::number(m_objectParam->GetY()));
    dom->setAttribute("w",QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h",QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name",m_objectParam->GetName());
}


